package com.sitech.openapi.componet;

import lombok.extern.slf4j.Slf4j;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.xpath.DefaultXPath;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.dom4j.Document;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class WSClientServiceImpl implements WSClientService {
    @Autowired
    private SoapClientService soapClientService;

    @Override
    public String doQryClientSerive(String inXml, String url) throws Exception{

        if (!inXml.contains("<![CDATA[")) {
            inXml = MessageFormat.format(crmXmlHead, inXml);
        }
        String resXmlString = null;
        try {
            resXmlString = soapClientService.remoteSoapClientInfo(url, inXml);
        } catch (Exception e) {
            log.error("", e);
            throw e;
        }
        log.info("==========出参===========");
        log.info(resXmlString);
        String soapBodyPath = "/soap:Envelope/soap:Body";

        Map<String, String> respNs = new HashMap<String, String>();
        String respXml = null;
        try {
            Document docOut = DocumentHelper.parseText(resXmlString);
            DefaultXPath xpath = new DefaultXPath(soapBodyPath);
            xpath.setNamespaceURIs(soapClientService.addSoapNameSpace(""));
            Node node = xpath.selectSingleNode(docOut);
            //添加 Envelope与 Body  的命名空间
            soapClientService.addNameSpace(docOut.getRootElement(), respNs);
            soapClientService.addNameSpace((Element) node, respNs);

            Map<String, Object> tempMap = new HashMap<String, Object>(3);
            int leafNodeNum = 0;
            tempMap.put("leafNodeNum", leafNodeNum);// 叶子节点的个数,
            soapClientService.getElementList((Element) node, tempMap, respNs);
            respXml = tempMap.get("respXml").toString();
        }catch(Exception e){
            log.error("", e);
            throw e;
        }
        return respXml;
    }
}
